package com.hyhy.hycloud.uaa.security.crypto;

import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.security.MessageDigest;

/**
 * 自定义MD5 PasswordEncoder
 *
 * @author Xuegui Yuan
 * @date 2018-09-19
 */
public class Md5PasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        MessageDigest md5;

        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception var8) {
            throw new IllegalArgumentException("No such algorithm [MD5]");
        }

        byte[] md5Bytes = md5.digest(Utf8.encode(rawPassword));
        return new String(Hex.encode(md5Bytes));
    }


    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String rawPasswordEncoded = encode(rawPassword);
        return rawPasswordEncoded.equals(encodedPassword);
    }

}
